package cn.wolfcode.crm.service.impl;


import cn.wolfcode.crm.domain.Product;
import cn.wolfcode.crm.mapper.ProductMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IProductService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Collections;
import java.util.List;

@Service
public class ProductServiceImpl implements IProductService {

	@Autowired
	private ProductMapper productMapper;


	public List<Product> selectAll() {
		return productMapper.selectAll();
	}

	public PageResult query(QueryObject qo) {
		int count = productMapper.queryForCount(qo);
		if (count == 0) {
			return new PageResult(count, Collections.EMPTY_LIST);
		}
		List<Product> result = productMapper.queryForList(qo);
		return new PageResult(count, result);
	}

	public void saveOrUpdate(Product record) {
		if (record.getId() != null) {
			productMapper.updateByPrimaryKey(record);
		} else {
			productMapper.insert(record);
		}
	}

	public void deleteByPrimaryKey(Long id) {
		productMapper.deleteByPrimaryKey(id);
	}

	public Product selectByPrimaryKey(Long id) {
		return productMapper.selectByPrimaryKey(id);
	}

	@Override
	public String saveBillAndProductRelation(Long[] ids) {

		if(ids != null){

			int random = (int) ((Math.random() * 9 + 1) * 100000);
			Calendar calendar=Calendar.getInstance();
			String number=calendar.get(Calendar.YEAR)+""+random;
			Long snNumber = Long.parseLong(number);
			for (Long id : ids) {
				productMapper.saveBillAndProductRelation(snNumber,id);
			}
			return String.valueOf(snNumber);
		}
		return null;

	}

	@Override
	public List<Product> selectProductListByBillNumber(Long number) {

		return productMapper.selectProductListByBillNumber(number);
	}

}
